package com.vnp.vchat.adapter;

import java.util.ArrayList;
import java.util.Hashtable;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap.Config;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.PointF;
import android.graphics.Typeface;
import android.os.Handler;
import android.text.util.Linkify;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;
import com.vnp.vchat.ChatActivity;
import com.vnp.vchat.R;
import com.vnp.vchat.ViewPhotoActivity;
import com.vnp.vchat.UIControls.MyCircleImageView;
import com.vnp.vchat.UIControls.MyClickAbleImageView;
import com.vnp.vchat.Util.PreferenceHelper;
import com.vnp.vchat.Util.Utils;
import com.vnp.vchat.bean.ObjMsgChat;

public class ChatAdapter extends ArrayAdapter<ObjMsgChat> {

	Context context;
	PreferenceHelper preferenceHelper;
	ArrayList<ObjMsgChat> objMsgChats = new ArrayList<ObjMsgChat>();
	boolean isFirst = true;

	private int lastPosition = -1;

	Matrix matrix = new Matrix();
	Matrix savedMatrix = new Matrix();
	PointF startPoint = new PointF();
	PointF midPoint = new PointF();
	float oldDist = 1f;
	static final int NONE = 0;
	static final int DRAG = 1;
	static final int ZOOM = 2;
	int mode = NONE;
	
	boolean isClicked = false;
	
	Runnable rE = new Runnable() {
		
		@Override
		public void run() {
			isClicked = false;
		}
	};
	
	Handler mHandler = new Handler();
	

	DisplayImageOptions optionsM = new DisplayImageOptions.Builder()
			.cacheInMemory(false).cacheOnDisc(true)
			.bitmapConfig(Config.RGB_565)
			.showImageForEmptyUri(R.drawable.bb_blue)
			.showImageOnLoading(R.drawable.bb_blue)
			.displayer(new RoundedBitmapDisplayer((int) 30f))
//			.displayer(new FadeInBitmapDisplayer(300, true, false, false))
			.build();
	
	DisplayImageOptions optionsF = new DisplayImageOptions.Builder()
								.cacheInMemory(false).cacheOnDisc(true)
								.bitmapConfig(Config.RGB_565)
								.showImageForEmptyUri(R.drawable.bb_gray)
								.showImageOnLoading(R.drawable.bb_gray)
								.displayer(new RoundedBitmapDisplayer((int) 30f))
							//	.displayer(new FadeInBitmapDisplayer(300, true, false, false))
								.build();
	
	DisplayImageOptions options1 = new DisplayImageOptions.Builder()
									.cacheInMemory(true).cacheOnDisc(true)
									.bitmapConfig(Config.RGB_565)
									.showImageForEmptyUri(R.drawable.image_default)
									.build();
	
	Hashtable<String, View> msgStatus = new Hashtable<String, View>();

	public ChatAdapter(Context context, ArrayList<ObjMsgChat> objMsgChats) {
		super(context, R.layout.item_chat, objMsgChats);
		this.context = context;
		this.objMsgChats = objMsgChats;
		preferenceHelper = new PreferenceHelper(context);
	}

	@Override
	public int getCount() {
		return objMsgChats.size();
	}

	@Override
	public ObjMsgChat getItem(int position) {
		return objMsgChats.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(final int position, View v, ViewGroup parent) {
		Holder holder = null;
		if (v == null) {
			LayoutInflater inflater = LayoutInflater.from(getContext());
			v = inflater.inflate(R.layout.item_chat, parent, false);
			holder = new Holder();

			holder.mine = (ViewGroup) v.findViewById(R.id.mine);
			holder.friend = (ViewGroup) v.findViewById(R.id.friend);

			holder.imgAvataFriend = (MyCircleImageView) v.findViewById(R.id.avatar_khach_hang);
			
			holder.imgPhotoKH = (MyClickAbleImageView) v.findViewById(R.id.img_KH);
			holder.imgPhoto = (MyClickAbleImageView) v.findViewById(R.id.img_mine);
			
			holder.txtMsgKH = (TextView) v.findViewById(R.id.txt_msg_khach_hang);
			holder.txtMsg = (TextView) v.findViewById(R.id.txt_msg);
			
			holder.txtMyTime = (TextView) v.findViewById(R.id.txt_my_time);
			holder.txtTimeFriend = (TextView) v.findViewById(R.id.txt_friend_time);
			
			holder.icMyTime = (ImageView) v.findViewById(R.id.ic_my_time);
			holder.icFriendTime = (ImageView) v.findViewById(R.id.ic_friend_tiem);
			
			holder.txtStatus = (TextView) v.findViewById(R.id.status);
			
			holder.icError = (ImageView) v.findViewById(R.id.ic_error);

			v.setTag(holder);
		} else {
			holder = (Holder) v.getTag();
		}

		// setfont
		holder.txtMsgKH.setTypeface(Utils.getTypefaceRegular(context), Typeface.BOLD);
		holder.txtMsg.setTypeface(Utils.getTypefaceRegular(context), Typeface.BOLD);
		holder.txtMyTime.setTypeface(Utils.getTypefaceLight(context));
		holder.txtTimeFriend.setTypeface(Utils.getTypefaceLight(context));

		final ObjMsgChat objMsgChat = objMsgChats.get(position);
		
//		Log.i("DATA", "Check id cua người gửi: " +objMsgChat.getFromId()+ " Content: "+objMsgChat.getContent());
		

		if (objMsgChat.getFromId().equals(preferenceHelper.getUserId())) {
			holder.mine.setVisibility(View.VISIBLE);
			holder.friend.setVisibility(View.GONE);
			
//			msgStatus.put(objMsgChat.getMsgID(), holder.txtStatus);
			
			// check status
			switch (objMsgChat.getStatus()) {
			case 0:
				holder.icError.setVisibility(View.VISIBLE);
				holder.txtStatus.setVisibility(View.GONE);
				holder.icError.setImageResource(R.drawable.ic_danggui);
//				holder.txtStatus.setText("...");
				break;
			case 1:
				holder.icError.setVisibility(View.GONE);
				holder.txtStatus.setVisibility(View.GONE);
				break;
			case 2:
				holder.icError.setVisibility(View.VISIBLE);
				holder.txtStatus.setVisibility(View.GONE);
				break;
			default:
				break;
			}
			
			if (position == 0){
				holder.txtMsg.setBackgroundResource(R.drawable.blue_nhon);
			}
			
			if (position > 0){
				if (objMsgChats.get(position-1).getFromId().equals(preferenceHelper.getUserId())){
					holder.txtMsg.setBackgroundResource(R.drawable.bb_blue);
				} else {
					holder.txtMsg.setBackgroundResource(R.drawable.blue_nhon);
				}
			}
			if (objMsgChat.getType().equalsIgnoreCase("image")){
				holder.imgPhoto.setVisibility(View.VISIBLE);
				holder.txtMsg.setVisibility(View.GONE);
				holder.imgPhoto.setPadding(15, 10, 10, 10);
				ImageLoader.getInstance().displayImage(objMsgChat.getUrlImageKH(), holder.imgPhoto, optionsM);
			} else {
				holder.imgPhoto.setVisibility(View.GONE);
				holder.txtMsg.setVisibility(View.VISIBLE);
				holder.txtMsg.setText(objMsgChat.getContent());
				Linkify.addLinks(holder.txtMsg, Linkify.ALL);
				holder.txtMsg.setLinkTextColor(Color.WHITE);
			}
			
			
			/*if ((position + 1) < objMsgChats.size()){
				if (objMsgChats.get(position+1).getFromId().equals(preferenceHelper.getUserId())){
					holder.txtMyTime.setVisibility(View.GONE);
					holder.icMyTime.setVisibility(View.GONE);
				} else {
					holder.txtMyTime.setVisibility(View.VISIBLE);
//					holder.txtMyTime.setText(Utils.getTimeAgoAsString(Utils.getCurrentTime()-objMsgChat.getTime()));
					holder.icMyTime.setVisibility(View.VISIBLE);
				}
			} else {
				
			}*/
			
		} else {
			holder.mine.setVisibility(View.GONE);
			holder.friend.setVisibility(View.VISIBLE);
			
			/*if (position == 0){
				if((position+1)>=objMsgChats.size()){
					holder.txtTimeFriend.setVisibility(View.VISIBLE);
//					holder.txtTimeFriend.setText(Utils.getTimeAgoAsString(Utils.getCurrentTime()-objMsgChat.getTime()));
				} else {
					holder.txtTimeFriend.setVisibility(View.GONE);
				}
			}*/
			

			if (position > 0){
				
				if (objMsgChats.get(position-1).getFromId().equals(preferenceHelper.getUserId())){
//					holder.imgAvataFriend.setVisibility(View.VISIBLE);
//					ImageLoader.getInstance().displayImage(objMsgChat.getUrlAvatarKhachhang(), holder.imgAvataFriend,options1);
					holder.txtMsgKH.setBackgroundResource(R.drawable.bb_gray_nhon);
				} else {
//					holder.imgAvataFriend.setVisibility(View.INVISIBLE);
					holder.txtMsgKH.setBackgroundResource(R.drawable.bb_gray);
				}
				
				/*if ((position + 1) < objMsgChats.size()){
					
					if (objMsgChats.get(position+1).getFromId().equals(preferenceHelper.getUserId())){
						holder.txtTimeFriend.setVisibility(View.VISIBLE);
//						holder.txtTimeFriend.setText(Utils.getTimeAgoAsString(Utils.getCurrentTime()-objMsgChat.getTime()));
					} else {
						holder.txtTimeFriend.setVisibility(View.GONE);
					}
					
				} else {
					
				}
				*/
				
				
			} else {
//				holder.imgAvataFriend.setVisibility(View.VISIBLE);
//				ImageLoader.getInstance().displayImage(objMsgChat.getUrlAvatarKhachhang(), holder.imgAvataFriend,options1);
				holder.txtMsgKH.setBackgroundResource(R.drawable.bb_gray_nhon);
			}
			
			
			
			// doi image
			
			Log.i("vChat", "Link anh: "+objMsgChat.getUrlImageKH());
			
			if (objMsgChat.getType().equalsIgnoreCase("image")) {
				holder.txtMsgKH.setVisibility(View.GONE);
				holder.imgPhotoKH.setVisibility(View.VISIBLE);
				holder.imgPhotoKH.setPadding(10, 10, 15, 10);
				ImageLoader.getInstance().displayImage(objMsgChat.getUrlImageKH(), holder.imgPhotoKH, optionsF);
				
			} else {
				holder.txtMsgKH.setVisibility(View.VISIBLE);
				holder.imgPhotoKH.setVisibility(View.GONE);
				holder.txtMsgKH.setText(objMsgChat.getContent());
				Linkify.addLinks(holder.txtMsgKH, Linkify.ALL);
			}
		}

		// Animation
		Animation animation = AnimationUtils.loadAnimation(getContext(),
				(position > lastPosition) ? R.anim.listview_up_from_bottom
						: R.anim.listview_down_from_bottom);
		/*if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
			v.startAnimation(animation);
		}*/
		lastPosition = position;
		
		 /*holder.imgPhotoKH.setOnClickListener(new OnClickListener() {
		  
		  @Override public void onClick(View v) {
			  
		  isClicked = true;
		  setEnableImage();
		  Intent t = new Intent(context, ViewPhotoActivity.class);
		  ChatActivity.onShow = true;
		  t.putExtra("url", objMsgChat.getUrlImageKH());
		  context.startActivity(t); 
		  
		  ((Activity) getContext()).overridePendingTransition(R.anim.zoom_enter, R.anim.zoom_out);
		  } });
		 
		 if (isClicked == true){
			 
		 } else {
			 holder.imgPhoto.setOnClickListener(new OnClickListener() {
					
					@Override
					public void onClick(View arg0) {
						ChatActivity.onShow = true;
						Intent t = new Intent(context, ViewPhotoActivity.class);
						  t.putExtra("url", objMsgChat.getUrlImageKH());
						  context.startActivity(t); 
						  ((Activity) getContext()).overridePendingTransition(R.anim.zoom_enter, R.anim.zoom_out);
					}
				});

		}*/
		
		OnClickListener myOnClickListener = new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if (isClicked == false){
					ChatActivity.onShow = true;
					isClicked = true;
					Intent t = new Intent(context, ViewPhotoActivity.class);
					t.putExtra("url", objMsgChat.getUrlImageKH());
					context.startActivity(t); 
					setEnableImage();
//					((Activity) getContext()).overridePendingTransition(R.anim.zoom_enter, R.anim.zoom_out);
					((Activity) getContext()).overridePendingTransition(R.anim.trans_left_in, R.anim.over_main_left);
				} else {
					
				}
			}
		};
			
		holder.imgPhoto.setOnClickListener(myOnClickListener);
		holder.imgPhotoKH.setOnClickListener(myOnClickListener);

		return v;
	}

	class Holder {
		ViewGroup friend, mine;
		MyCircleImageView imgAvataFriend;
		TextView txtMsg, txtMsgKH, txtTimeFriend, txtMyTime, txtStatus;
		MyClickAbleImageView imgPhotoKH, imgPhoto;
		ImageView icMyTime,icFriendTime, icError;
	}
	
	public void updateStatusMsg(final ObjMsgChat objMsgChat){
		
		((Activity) context).runOnUiThread(new Runnable() {
			
			@Override
			public void run() {
				View v = msgStatus.get(objMsgChat.getMsgID());
				final TextView title = (TextView) v.findViewById(R.id.status);
				
				int status = objMsgChat.getStatus();
				switch (status) {
				case 0:
					title.setText("...");
					break;
				case 1:
					title.setVisibility(View.GONE);
					break;
				case 2:
					title.setText("X");
					break;
				default:
					break;
				}
			}
		});
	}
	
	void setEnableImage(){
		mHandler.removeCallbacks(rE);
		mHandler.postDelayed(rE, 1000);
	}
	
	public void removeHanlder(){
		mHandler.removeCallbacks(rE);
	}
}
